package cqgans.app.sunao.com.cqgans.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;

import cqgans.app.sunao.com.cqgans.adapter.ProductAdapter;
import cqgans.app.sunao.com.cqgans.bean.Product;
import cqgans.app.sunao.com.cqgans.common.AppConstant;
import cqgans.app.sunao.com.cqgansnew.R;

import static cqgans.app.sunao.com.cqgans.common.AppConstant.isCom;

/**
 * Created by sunao on 2017/6/14.
 */
@SuppressWarnings("WrongConstant")
@ContentView(R.layout.product)
public class ProductActivity extends BaseActivity {
    @ViewInject(R.id.product_account_name)
    private TextView product_account_name;
    @ViewInject(R.id.product_list)
    private ListView product_list;
    private ProductAdapter mAdapter;
    private ArrayList<Product> mlist;
    @ViewInject(R.id.product_loading)
    private RelativeLayout product_loading;
    @ViewInject(R.id.back)
    private TextView backbtn;
    @ViewInject(R.id.refresh_layout)
    private SwipeRefreshLayout refresh_layout;
    @ViewInject(R.id.product_account_type)
    private TextView product_account_type;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    int userType = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        setTitleBar("产品列表", 5);
        initLayout();
    }

    private void initLayout() {
        mAdapter = new ProductAdapter(this);
        product_list.setAdapter(mAdapter);
        this.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        userType = getIntent().getIntExtra("userType", -1);
        if(userType != -1) {
            product_account_name.setText("");
            product_account_type.setText(userType == 1 ? "工商用户" : "个人用户");
        } else {
            product_account_name.setText(AppConstant.account!=null?(AppConstant.account.userName):"");
            product_account_type.setText(AppConstant.account!=null?(AppConstant.account.userType == 1 ? "工商用户" : "个人用户"):"");
        }
        getData();
        refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh_layout.setRefreshing(true);
                getData();
                ( new Handler()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh_layout.setRefreshing(false);

                    }
                }, 3000);


            }

        });

        product_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Product p = mAdapter.getItem(i);
                if (p != null && !TextUtils.isEmpty(p.getProductId())) {
                    AppConstant.TARGET_URL = AppConstant.JSS_PRODUCT_SHOW_URL;
                    Intent it = new Intent(ProductActivity.this, WebActivity.class);
                    it.putExtra("productNo", p.getProductId());
                    startActivity(it);
                }

            }
        });
        product_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0)
                    refresh_layout.setEnabled(true);
                else
                    refresh_layout.setEnabled(false);
            }
        });
        findViewById(R.id.user_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AppConstant.TARGET_URL = AppConstant.JSS_ACCOUNT_URL;
                startActivity(new Intent(ProductActivity.this, WebActivity.class));

            }
        });


        if (!AppConstant.isHomePage){
            sharedPreferences = getSharedPreferences("cqgas", Context.MODE_PRIVATE);
            TextView close = (TextView) this.findViewById(R.id.close);
//            close.setVisibility(View.VISIBLE);
//            close.setText("切换账号");
//            close.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    AppConstant.user = null;
//                    editor = sharedPreferences.edit();//获取编辑器
//                    editor.putInt("id", 0);
//                    editor.commit();
//                    startActivity(new Intent(ProductActivity.this, MainActivity.class));
//                    finish();
//                }
//            });
        }

    }

    private void getData() {
        {
            product_loading.setVisibility(View.VISIBLE);

            RequestParams params = new RequestParams(AppConstant.URL + AppConstant.PRODUCT_URL);
//        params.addQueryStringParameter("userCode",s);
//        params.addQueryStringParameter("staffMobile",AppConstant.user.getMobile());
            JSONObject mjson = new JSONObject();

            try {
                mjson.put("pageSize", 30);
                mjson.put("pageNo", 1);
                String usrType = "";
                if (AppConstant.isHomePage){
                    if(userType != -1) {
                        usrType = userType + "";
                    } else {
                        usrType = AppConstant.account.userType + "";
                    }
                }else{
                    if (isCom){
                        usrType = "1";
                    }else{
                        usrType = "2";
                    }
                    mjson.put("loginUserPhone", getSharedPreferences("cqgas", Context.MODE_PRIVATE).getString("mobile", ""));
                }
                mjson.put("userType",usrType);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            params.setAsJsonContent(true);
            params.setBodyContent(mjson.toString());
            params.addHeader("Content-Type", "application/json");
            x.http().post(params, new Callback.CommonCallback<String>() {
                @SuppressWarnings("WrongConstant")
                @Override
                public void onSuccess(String result) {
                    LogUtil.i(result);
                    System.out.println(result);
                    product_loading.setVisibility(View.GONE);
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        LogUtil.i(resultJson.toString());
                        if (resultJson.has("flag") && resultJson.getBoolean("flag")) {
                            Gson gson = new Gson();
                            if (resultJson.has("data")) {
                                JSONObject data = resultJson.getJSONObject("data");
                                JSONObject page = data.getJSONObject("page");
                                JSONArray pageResults = page.getJSONArray("pageResults");
                                Type type = new TypeToken<ArrayList<Product>>() {
                                }.getType();

                                mlist = gson.fromJson(pageResults.toString(), type);
                                mAdapter.setItems(mlist);
                                mAdapter.notifyDataSetChanged();

                            }
                        } else {
                            product_loading.setVisibility(View.INVISIBLE);
                            Toast.makeText(ProductActivity.this, "产品列表查询失败", 1000).show();
                        }

                    } catch (JSONException e) {
                        product_loading.setVisibility(View.INVISIBLE);

                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    product_loading.setVisibility(View.GONE);
                    LogUtil.e(ex.getMessage());
                    Toast.makeText(ProductActivity.this, ex.getMessage(), 1000).show();

                }

                @Override
                public void onCancelled(CancelledException cex) {
                    product_loading.setVisibility(View.GONE);

                }

                @Override
                public void onFinished() {
                    refresh_layout.setRefreshing(false);
                }
            });

        }
    }


}
